package com.education.service.system;

import com.education.common.exception.BusinessException;
import com.education.common.utils.ObjectUtils;
import com.education.common.utils.Result;
import com.education.common.utils.ResultCode;
import com.education.mapper.system.SystemRoleMapper;
import com.education.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 角色管理业务层
 * @author Jason
 * @version 1.0.0
 * @date 2021-11-24 21:05
 */
@Service
public class SystemRoleService extends BaseService<SystemRoleMapper> {

    @Autowired
    private SystemRoleMenuService systemRoleMenuService;
    @Autowired
    private SystemAdminRoleService systemAdminRoleService;

    public Result queryList(Map params) {
        return super.pagination(params);
    }

    @Override
    public Result saveOrUpdate(Map modelBeanMap) {
        synchronized (this) {
            // 检查角色是否存在
            Map roleMap = mapper.findByRoleName((String) modelBeanMap.get("name"));
            if (ObjectUtils.isNotEmpty(roleMap) &&
                    !roleMap.get("id").equals(modelBeanMap.get("id"))) {
                return Result.fail(ResultCode.FAIL, "角色已存在，请勿重复添加");
            }
        }
        return super.saveOrUpdate(modelBeanMap);
    }

    /**
     * 删除角色，因为对多表操作，为了保证数据的一致性，需要开启事务
     * @param roleId 角色id
     * @return
     */
    @Override
    @Transactional
    public Result deleteById(Integer roleId) {
        try {
            // 删除角色
            super.deleteById(roleId);
            // 删除角色关联的菜单
            systemRoleMenuService.deleteByRoleId(roleId);
            // 删除用户角色关联
            systemAdminRoleService.deleteByRoleId(roleId);
            return Result.success(ResultCode.SUCCESS, "删除角色成功");
        } catch (Exception e) {
            logger.error("删除角色异常", e);
            throw new BusinessException(new ResultCode(ResultCode.FAIL, "删除角色异常"));
        }
    }

    @Transactional
    public Result batchDeleteByRoleIds(List<Integer> roleIds) {
        try {
            // 批量删除角色
            super.batchDeleteByIds(roleIds);
            // 批量删除角色关联的菜单
            systemRoleMenuService.batchDeleteByRoleIds(roleIds);
            // 批量删除用户角色关联
            systemAdminRoleService.batchDeleteByRoleIds(roleIds);
            return Result.success(ResultCode.SUCCESS, "批量删除角色成功");
        } catch (Exception e) {
            logger.error("批量删除角色异常", e);
            throw new BusinessException(new ResultCode(ResultCode.FAIL, "批量删除角色异常"));
        }
    }
}
